<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="48">
          <a-col :md="8" :sm="24">
            <a-form-item label="昵称">
              <a-input v-model="queryParam.userName" placeholder="" />
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-item label="姓名">
              <a-input v-model="queryParam.realName" placeholder="" />
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-item label="唯一码">
              <a-input v-model="queryParam.uniCode" placeholder="" />
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-item label="所在高校">
              <!-- <a-input v-model="queryParam.universityId" placeholder="" /> -->
              <a-auto-complete
                placeholder="请输入高校名称进行搜索"
                @select="onSchoolSelect"
                @search="onSchoolSearch"
              >
                <template slot="dataSource">
                  <a-select-option v-for="item in schoolList" :key="item.universityId" :value="item.universityId">{{ item.universityName }}</a-select-option>
                </template>
              </a-auto-complete>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-item label="注册时间">
              <a-date-picker
                style="width: 46%"
                v-model="queryParam.startDate"
                placeholder="请输入开始时间"
                @change="onStartDateChange"
              />
              <a-input
                style="width: 8%; border-left: 0; pointer-events: none; backgroundcolor: #fff"
                placeholder="~"
                disabled
              />
              <a-date-picker
                style="width: 46%"
                v-model="queryParam.endDate"
                placeholder="请输入结束时间"
                @change="onEndDateChange"
              />
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <span class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchBtn">查询</a-button>
              <a-button style="margin-left: 8px" @click="() => (this.queryParam = {})">重置</a-button>
              <a-button
                type="danger"
                @click.stop="exportExcel"
                style="margin-left:8px"
                :loading="exportLoading"
                :disabled="exportLoading"
              >
                <a-icon type="cloud-download" style="color:white"/>
                <span>导出</span>
              </a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <a-table
      ref="table"
      :row-key="
        (record) => {
          return record.userId
        }
      "
      :columns="columns"
      :data-source="data"
      :loading="loading"
      :pagination="pagination"
      @change="onChange"
    >
      <span slot="headImg" slot-scope="text, record">
        <img :src="record.headImg" style="width: 50px; height: 50px" v-if="record.headImg" />
      </span>
      <span slot="action" slot-scope="text, record">
        <template>
          <router-link :to="{ name: 'UserDetail', params: { id: record.userId } }">查看</router-link>
          <a-divider type="vertical" />
          <a @click="changeIntegral(record.userId)">改变积分</a>
          <a-divider type="vertical" />
          <a @click="deleteOne(record.userId)">删除</a>
        </template>
      </span>
    </a-table>

    <create-form ref="createModal" :visible="visible" :model="mdl" @cancel="visible = false" @ok="visible = false" />
  </a-card>
</template>

<script>
import moment from 'moment'
const CreateForm = () => import('./modules/IntegralForm')
const columns = [
  {
    title: '序号',
    dataIndex: 'userId'
  },
  {
    title: '唯一码',
    dataIndex: 'uniCode'
  },
  {
    title: '昵称',
    dataIndex: 'userName'
  },
  {
    title: '姓名',
    dataIndex: 'realName'
  },
  {
    title: '手机号',
    dataIndex: 'phone'
  },
  {
    title: '所在高校',
    dataIndex: 'universityName'
  },
  {
    title: '头像',
    dataIndex: 'headImg',
    scopedSlots: { customRender: 'headImg' }
  },
  {
    title: '总积分',
    dataIndex: 'totalCredit',
    sorter: true,
    sortDirections: ['descend', 'ascend']
  },
  {
    title: '已助力积分',
    dataIndex: 'donateCredit'
  },
  {
    title: '可助力积分',
    dataIndex: 'availCredit'
  },
  {
    title: '创建时间',
    dataIndex: 'createdAt'
  },
  {
    title: '操作',
    key: 'action',
    scopedSlots: { customRender: 'action' }
  }
]

export default {
  name: 'UserList',
  components: {
    CreateForm
  },
  data() {
    return {
      url: '',
      columns,
      loading: false,
      data: [],
      pagination: {
        showQuickJumper: true,
        showSizeChanger: true,
        defaultCurrent: 1, // 默认当前页数
        defaultPageSize: 10, // 默认当前页显示数据的大小
        total: 0, // 总数，必须先有
        pageSizeOptions: ['10', '20', '30', '50', '100'],
        showTotal: (total, range) => {
          return (
            <div>
              共 <span>{total}</span> 条
            </div>
          )
        },
        onShowSizeChange: (current, pageSize) => {
          this.pageSize = pageSize
        }
      },
      queryParam: {},
      queryOrder: {},
      userStatus: [
        { value: 1, label: '启用' },
        { value: 0, label: '禁用' }
      ],
      visible: false,
      mdl: {},
      schoolList: [], // 高校列表
      exportLoading: false // 导出状态
    }
  },
  created() {
  },
  mounted() {
    // 获取列表
    this.fetch()
  },
  methods: {
    // 开始时间
    onStartDateChange(data, dataString) {
      this.queryParam.startDate = dataString
    },
    // 结束时间
    onEndDateChange(data, dataString) {
      this.queryParam.endDate = dataString
    },
    // 搜索学校
    onSchoolSearch(searchText) {
      this.queryParam.universityId = ''
      this.schoolList = []
      if (searchText) {
        const query = {
					page: 1,
					pagesize: 20,
					keywords: searchText
				}
        this.$common.handleGet('/university/index', query).then(res => {
          if (res.code === 200) {
            this.schoolList = res.data.lists
          }
        })
      }
    },
    onSchoolSelect(value) {
      // console.log('onSelect', value)
      this.queryParam.universityId = value
    },
    // 改变每页数量时更新显示
    onChange(pagination, filters, sorter) {
      console.log(pagination, filters, sorter)
      this.pagination.defaultCurrent = pagination.current
      this.pagination.defaultPageSize = pagination.pageSize
      if (sorter.field && sorter.field === 'totalCredit') {
        if (sorter.order === 'descend') {
          this.queryOrder.creditOrder = 2
        } else if (sorter.order === 'ascend') {
          this.queryOrder.creditOrder = 1
        } else {
          this.queryOrder = {}
        }
      }
      this.fetch()
    },
    // 搜索
    searchBtn() {
      this.pagination.defaultCurrent = 1
      this.fetch()
    },
    // 动态获取列表
    fetch() {
      this.loading = true
      const params = {
        page: this.pagination.defaultCurrent,
        pagesize: this.pagination.defaultPageSize
      }
      this.$common
        .handlePost('/user/list', Object.assign({}, params, this.queryParam, this.queryOrder))
        .then((res) => {
          this.loading = false
          if (res.code === 200) {
            const result = res.data
            const pagination = { ...this.pagination }
            pagination.total = result.totalInfo.total
            this.data = result.records
            this.pagination = pagination
          }
        })
        .catch(() => {
          this.$notification.error({
            message: '错误',
            description: '请求信息失败，请重试'
          })
        })
    },
    // 启用、禁用
    changeStatus(id, status) {
      if (id && status !== '') {
        // var statusVal = ENABLE
        var message = ''
        var url = ''
        if (status) {
          message = '确定要启用吗？'
          url = '/user/open/'
        } else {
          message = '确定要禁用吗？'
          url = '/user/close/'
          //   statusVal = DISABLE
        }
        const _this = this
        this.$confirm({
          title: message,
          onOk() {
            _this.$common
              .handlePost(url + id)
              .then((data) => {
                if (data.code === 200) {
                  _this.$message.success(data.message)
                  _this.fetch()
                } else {
                  _this.$message.error(data.message)
                }
              })
              .catch(() => {
                _this.$notification.error({
                  message: '错误',
                  description: '请求信息失败，请重试'
                })
              })
          },
          onCancel() {
            console.log('Cancel')
          },
          class: 'test'
        })
      } else {
        this.$message.error('参数错误')
      }
    },
    // 改变积分
    changeIntegral(id) {
      this.mdl = {
        id,
        type: 1,
        credit: '',
        remark: ''
      }
      this.visible = true
    },
    // 导出
    exportExcel() {
      this.exportLoading = true
      this.$common.exportExcel('users/export', this.queryParam)
      .then(res => {
        this.exportExcelFile(res)
      })
      .finally(() => {
        this.exportLoading = false
      })
    },
    exportExcelFile (exportData) {
      const link = document.createElement('a')
      // type就是blob的type,是MIME类型的，可以自己查看MIME类型都有哪些
      const blogw = new Blob([exportData], { type: 'application/vnd.ms-excel;charset=utf-8' })
      const objectUrl = window.URL.createObjectURL(blogw) // 创建一个新的url对象
      link.href = objectUrl
      const fileName = `用户 ${moment().format('YYYYMMDDHHmmss')}.xlsx`
      link.download = fileName // 下载的时候自定义的文件名
      link.click()
      window.URL.revokeObjectURL(objectUrl) // 为了更好地性能和内存使用状况，应该在适当的时候释放url.
      this.fetch()
    },
    // 删除某一个
    deleteOne(id) {
      this.handleDelete(id)
    },
    handleDelete(deleteId) {
      this.$common
        .deleteOne('/user/delete/' + deleteId, {}, deleteId)
        .then((res) => {
          if (res) {
            this.fetch()
          }
        })
        .catch(() => {
          this.$notification.error({
            message: '错误',
            description: '请求信息失败，请重试'
          })
        })
    }
  }
}
</script>
